package com.example.luohao.myservicedemo;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mBT_Start_service;
    private View mBT_close_service;
    private Intent intent1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initView() {
        mBT_Start_service = findViewById(R.id.mBT_start_service);
        mBT_Start_service.setOnClickListener(this);
        mBT_close_service = findViewById(R.id.mBT_close_service);
        mBT_close_service.setOnClickListener(this);
    }

    private void initData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mBT_start_service:
                intent1 = new Intent(this, MyService.class);
                /*使用startService()开启服务后必须使用stopService()才能关闭服务，服务走onDestroy()*/
                //                startService(intent1);
                /*不使用startService(),直接使用bindServi(),开启服务，不调用服务的onStartCommand(),直接unbindService()解绑服务后会走onDestroy()*/
                bindService(intent1, serviceConnection, BIND_AUTO_CREATE);
                break;
            case R.id.mBT_close_service:
                /*使用startService()+bindService()开启的服务，必须stopService()+bindService()解绑关闭服务，只执行stopService(),
                没有反应，只执行unbindService(),解绑了Activity与服务，并没有销毁服务，不走onDestroy()*/
                //                stopService(intent1);
                /*unbindService()不可多次解绑，否则崩溃*/
                unbindService(serviceConnection);
                break;
        }
    }

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MyService.MyBinder myBinder = (MyService.MyBinder) iBinder;
            myBinder.startDownload();
            MyService service = myBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
}
